import { createRouter, createWebHistory } from 'vue-router'
import registration from '@/views/RegistrationPage.vue'
import login from '@/views/Login.vue'
import index from '@/views/Index.vue'
import { useTokenStore } from '@/stores/tokenStore'
import homePage from '@/views/HomePage.vue'
import profile from '@/views/Profile.vue'
import article from '@/views/Article.vue'
import editArticle from '@/components/EditArticle.vue'
import publishSuccess from '../views/PublishSuccess.vue'
import PrivateMessagePage from '@/components/PrivateMessagePage.vue'

const router = createRouter({
    history: createWebHistory(
        import.meta.env.BASE_URL),
    routes: [{
            path: '/',
            redirect: '/index'
        }, {
            path: '/registration',
            name: 'registration',
            component: registration,
        },
        {
            path: '/login',
            name: 'login',
            component: login,
        },
        {
            path: '/index',
            name: 'index',
            component: index,
        },
        {
            path: '/homePage/:id',
            name: 'homePage',
            component: homePage,
        },
        {
            path: '/profile',
            name: 'profile',
            component: profile,
        },
        {
            path: '/article/:id',
            name: 'article',
            component: article,
        },
        {
            path: '/editArticle/:id',
            name: 'EditArticle',
            component: editArticle,
        },
        {
            path: '/editArticle',
            name: 'CreateArticle',
            component: editArticle,
        },
        {
            path: '/publishSuccess/:articleId',
            name: 'publishSuccess',
            component: publishSuccess,
        },
        {
            path: '/privateMessagePage',
            name: 'privateMessagePage',
            component: PrivateMessagePage,
        },
    ],
})

// 白名单
const WHITE_LIST = ['/login', '/registration']

router.beforeEach((to) => {
    const { path } = to
    // 是白名单
    if (WHITE_LIST.includes(path)) {
        return true;
    }

    const tokenStore = useTokenStore()
        // console.log(tokenStore.token);

    if (tokenStore.token) {
        return true
    } else {
        // 没有 token 并且不是白名单
        return `/login?redirectUrl=${path}`
    }
})

export default router